﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FirstWinform
{
    class DBHelper
    {
        //鏁版嵁搴撹繛鎺ュ瓧绗︿覆
        public static string ConnString = "server=.;database=BooksDB;Integrated Security=True;";

        //鏁版嵁搴撹繛鎺ュ璞?
        public static SqlConnection Conn = null;

        //鍒濆鍖栨暟鎹簱杩炴帴
        public static void InitConnection()
        {
            //濡傛灉杩炴帴瀵硅薄涓嶅瓨鍦紝鍒欏垱寤鸿繛鎺?
            if (Conn == null)
                Conn = new SqlConnection(ConnString);
            //濡傛灉杩炴帴瀵硅薄鍏抽棴锛屽垯鎵撳紑杩炴帴
            if (Conn.State == ConnectionState.Closed)
                Conn.Open();
            //濡傛灉杩炴帴涓柇锛屽垯閲嶅惎杩炴帴
            if (Conn.State == ConnectionState.Broken)
            {
                Conn.Close();
                Conn.Open();
            }
        }

        //鏌ヨ锛岃幏鍙朌ataReader
        public static SqlDataReader GetDataReader(string sqlStr)
        {
            InitConnection();
            SqlCommand cmd = new SqlCommand(sqlStr, Conn);
            //CommandBehavior.CloseConnection 鍛戒护琛屼负锛氬綋DataReader瀵硅薄琚叧闂椂锛岃嚜鍔ㄥ叧闂崰鐢ㄧ殑杩炴帴瀵硅薄
            return cmd.ExecuteReader(CommandBehavior.CloseConnection);
        }

        //鏌ヨ锛岃幏鍙朌ataTable
        public static DataTable GetDataTable(string sqlStr)
        {
            InitConnection();
            DataTable table = new DataTable();
            SqlDataAdapter dap = new SqlDataAdapter(sqlStr, Conn);
            dap.Fill(table);
            Conn.Close();
            return table;
        }

        //澧炲垹鏀?
        public static bool ExecuteNonQuery(string sqlStr)
        {
            InitConnection();
            SqlCommand cmd = new SqlCommand(sqlStr, Conn);
            int result = cmd.ExecuteNonQuery();
            Conn.Close();
            return result > 0;
        }

        //鎵ц闆嗗悎鍑芥暟
        public static object ExecuteScalar(string sqlStr)
        {
            InitConnection();
            SqlCommand cmd = new SqlCommand(sqlStr, Conn);
            object result = cmd.ExecuteScalar();
            Conn.Close();
            return result;
        }
    }
}
